package phaseListener;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class PhaseListenerLogin implements PhaseListener{

	private static final long serialVersionUID = 8892109643245847618L;

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		String currentPage = facesContext.getViewRoot().getViewId();
		
		boolean isLoginPage = currentPage.lastIndexOf("login.xhtml")> -1;
		
		HttpSession sessao = (HttpSession) facesContext.getExternalContext().getSession(true);
		boolean userIsLogged = sessao.getAttribute("usuario") != null;
		
		if ((!isLoginPage) && (!userIsLogged)){
			NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
			nh.handleNavigation(facesContext, null, "login");
		}
	}

	@Override
	public void beforePhase(PhaseEvent arg0) {
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
